package com.ruoyi.disk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.disk.domain.SysBackup;
import com.ruoyi.disk.domain.dto.RestoreDTO;
import com.ruoyi.disk.service.ISysBackupService;

/**
 * 备份管理控制器
 */
@RestController
@RequestMapping({"/disk/backup", "/disk/storage/backups"})
public class SysBackupController extends BaseController {
    
    @Autowired
    private ISysBackupService sysBackupService;
    
    /**
     * 创建备份
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:create')")
    @Log(title = "创建备份", businessType = BusinessType.INSERT)
    @PostMapping("/{userId}")
    public AjaxResult createBackup(@PathVariable("userId") Long userId) {
        // 权限检查 - 只能备份自己的，或者管理员可以备份任何人的
        if (!SecurityUtils.isAdmin() && !userId.equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("没有权限备份其他用户的文件");
        }
        
        return AjaxResult.success(sysBackupService.createBackup(userId));
    }
    
    /**
     * 创建备份 - 兼容旧API
     */
    @PreAuthorize("@ss.hasPermi('disk:storage:backupDisk')")
    @Log(title = "创建备份", businessType = BusinessType.INSERT)
    @PostMapping("/backup/{userId}")
    public AjaxResult createBackupCompatibility(@PathVariable("userId") Long userId) {
        return createBackup(userId);
    }
    
    /**
     * 获取备份列表
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:list')")
    @GetMapping("/{userId}")
    public AjaxResult listBackups(@PathVariable("userId") Long userId) {
        // 权限检查 - 只能查看自己的，或者管理员可以查看任何人的
        if (!SecurityUtils.isAdmin() && !userId.equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("没有权限查看其他用户的备份");
        }
        
        return AjaxResult.success(sysBackupService.listUserBackups(userId));
    }
    
    /**
     * 获取备份文件列表
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:files')")
    @GetMapping("/{userId}/{backupId}/files")
    public AjaxResult listBackupFiles(@PathVariable("userId") Long userId, @PathVariable("backupId") String backupId) {
        // 权限检查 - 只能查看自己的，或者管理员可以查看任何人的
        if (!SecurityUtils.isAdmin() && !userId.equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("没有权限查看其他用户的备份文件");
        }
        
        return AjaxResult.success(sysBackupService.listBackupFiles(userId, backupId));
    }
    
    /**
     * 恢复备份文件
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:restore')")
    @Log(title = "恢复备份", businessType = BusinessType.UPDATE)
    @PostMapping("/restore")
    public AjaxResult restoreFiles(@RequestBody RestoreDTO restoreDTO) {
        // 权限检查 - 只能恢复自己的，或者管理员可以恢复任何人的
        if (!SecurityUtils.isAdmin() && !restoreDTO.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("没有权限恢复其他用户的备份");
        }
        
        return AjaxResult.success(sysBackupService.restoreFiles(restoreDTO));
    }
    
    /**
     * 恢复备份文件 - 兼容旧API
     */
    @PreAuthorize("@ss.hasPermi('disk:storage:restoreFiles')")
    @Log(title = "恢复备份", businessType = BusinessType.UPDATE)
    @PostMapping("/restore")
    public AjaxResult restoreFilesCompatibility(@RequestBody RestoreDTO restoreDTO) {
        return restoreFiles(restoreDTO);
    }
    
    /**
     * 删除备份
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:delete')")
    @Log(title = "删除备份", businessType = BusinessType.DELETE)
    @DeleteMapping("/{backupId}")
    public AjaxResult deleteBackup(@PathVariable("backupId") String backupId) {
        // 获取备份信息，检查权限
        SysBackup backup = sysBackupService.selectSysBackupById(backupId);
        if (backup == null) {
            return AjaxResult.error("备份不存在");
        }
        
        // 权限检查 - 只能删除自己的，或者管理员可以删除任何人的
        if (!SecurityUtils.isAdmin() && !backup.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("没有权限删除其他用户的备份");
        }
        
        return toAjax(sysBackupService.deleteSysBackupById(backupId));
    }
    
    /**
     * 批量删除备份
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:delete')")
    @Log(title = "批量删除备份", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch/{backupIds}")
    public AjaxResult deleteBackups(@PathVariable("backupIds") String[] backupIds) {
        // 批量删除前检查每个备份的权限
        for (String backupId : backupIds) {
            SysBackup backup = sysBackupService.selectSysBackupById(backupId);
            if (backup != null && !SecurityUtils.isAdmin() && !backup.getUserId().equals(SecurityUtils.getUserId())) {
                return AjaxResult.error("没有权限删除备份ID为" + backupId + "的备份");
            }
        }
        
        return toAjax(sysBackupService.deleteSysBackupByIds(backupIds));
    }
    
    /**
     * 查询所有备份
     */
    @PreAuthorize("@ss.hasPermi('disk:backup:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBackup sysBackup) {
        startPage();
        // 非管理员只能查看自己的备份
        if (!SecurityUtils.isAdmin()) {
            sysBackup.setUserId(SecurityUtils.getUserId());
        }
        return getDataTable(sysBackupService.selectSysBackupList(sysBackup));
    }
    
    /**
     * 兼容旧路径的删除备份接口
     */
    @PreAuthorize("@ss.hasPermi('disk:storage:backupDisk')")
    @Log(title = "删除备份", businessType = BusinessType.DELETE)
    @DeleteMapping("/backups/{backupId}")
    public AjaxResult deleteBackupStorage(@PathVariable("backupId") String backupId) {
        return deleteBackup(backupId);
    }
} 